package com.ljh.myrpc.server.tcp;

import com.ljh.myrpc.server.HttpServer;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;

import java.util.Arrays;

/**
 * TCP服务器实现
 */

public class VertxTcpServer implements HttpServer {

    private byte[] handleRequest(byte[] requestData){
        System.out.println("received response from server: " + Arrays.toString(requestData));


        return "hello, client".getBytes();
    }


    @Override
    public void doStart(int port) {
        // 创建 Vert.x 实例
        Vertx vertx = Vertx.vertx();
        // 创建TCP服务器
        NetServer netServer = vertx.createNetServer();

        netServer.connectHandler(new TcpServerHandle());
//        netServer.connectHandler(netSocket -> {
//            // 处理连接
//            netSocket.handler(buffer -> {
//                // 处理接收到的字节数组
//                byte[] requestData = buffer.getBytes();
//                // 在这里进行自定义的字节数组处理逻辑
//                byte[] responseData = handleRequest(requestData);
//                // 发送响应
//                netSocket.write(Buffer.buffer(responseData));
//            });
//        });

        // 启动TCP服务器并监听接口
        netServer.listen(port, result -> {
            if(result.succeeded()){
                System.out.println("TCP server started on port " + port);
            }else {
                System.out.println("TCP server failed to start: " + result.cause());
            }
        });
    }

    public static void main(String[] args){
        new VertxTcpServer().doStart(8888);
    }

}
